//
//  EMUploadProfile.m
//  PictureSelector
//
//  Created by Lyy on 15/8/26.
//  Copyright (c) 2015年 Lyy. All rights reserved.
//

#import "EMUploadProfile.h"
#import "EMPoperViewController.h"
#import "EMImageEditViewController.h"
#import <AFNetworking.h>

@interface EMUploadProfile ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIViewController *_controller;

}
@end

@implementation EMUploadProfile

//static EMUploadProfile *__uploadProfile = nil;
//
//+ (instancetype)shareManager {
//    
//    static dispatch_once_t predicate;
//    dispatch_once(&predicate, ^{
//        __uploadProfile = [[[EMUploadProfile class] alloc] init];
//    });
//    
//    return __uploadProfile;
//}

- (void)uploadProfile:(EMUploadProfileLoginType)loginType
           profileUrl:(NSString *)urlString
        rootViewController:(UIViewController *)rootViewContrller
            uploadComplete:(void (^)(UIImage *userProfileImage))uploadComplete {
    
    _controller = rootViewContrller;
    self.profileImage = uploadComplete;
    EMPoperViewController *poperViewController = [[EMPoperViewController alloc] initLoginType:loginType profileImageUrl:urlString];
    [rootViewContrller presentViewController:poperViewController animated:YES completion:nil];

    poperViewController.dismisss = ^(NSIndexPath *indexPath, UIImage *image){
        
        if (loginType != EMUploadProfileLoginOther && indexPath.row == 2) {
            [self openPhoto];
        } else if (loginType == EMUploadProfileLoginOther && indexPath.row == 1){
            [self openPhoto];
        }
        else {
            [self uploadImage:image];
        }
    };
}

//选取相册图片
- (void)openPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    [_controller presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
    EMImageEditViewController *imageEditVC = [[EMImageEditViewController alloc] initWithImage:image complete:^(UIImage *clippedImage) {
        [_controller dismissViewControllerAnimated:YES completion:^{
            _profileImage(clippedImage);
//            [self uploadImage:clippedImage];
        }];

    }];
    
    [picker pushViewController:imageEditVC animated:YES];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    NSLog(@"--------uploadProfile--------------");
}

// 上传头像
- (void)uploadImage:(UIImage *)image
{
    
    //    上传多个文件
    //    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    //    } error:nil];
    //    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    //    上传单个文件
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
            self.profileImage(image);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
            
            self.profileImage(image);
            //            self.clipeImage(image);
            
        }
    }];
    [uploadTask resume];
}


- (void)add {
    //         //配置文件上传
    //
    //         //图片data 上传
    //         //UIImage *upImage = [UIImage imageNamed:@"testImage.png"];
    //         //NSData *imageData = UIImagePNGRepresentation(upImage);
    //
    //         //文件file上传，上传mp3音乐文件
    //    //NSString *theUpFilePath = [NSString stringWithFormat:@"%@testMusic.mp3",NSTemporaryDirectory()];
    //
    //        //上传个图片文件；
    //         NSString *theImagePath = [[NSBundle mainBundle] pathForResource:@"testImage" ofType:@"png"];
    //
    //         self.uploadFileClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@""]];//kCOCOA_FileUPload
    //         NSMutableURLRequest *fileUpRequest = [_uploadFileClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:nil constructingBodyWithBlock:^(id formData) {
    //
    //                 //[formData appendPartWithFileData:imageData name:@"file" fileName:@"testImage" mimeType:@"image/png"];
    //
    //                 //[formData appendPartWithFileURL:[NSURL fileURLWithPath:theUpFilePath isDirectory:NO] name:@"file" fileName:@"testMusic.mp3" mimeType:@"audio/mpeg3" error:nil];
    //
    //                 [formData appendPartWithFileURL:[NSURL fileURLWithPath:theImagePath] name:@"file" error:nil];
    //
    //             }];
    //
    //         self.fileUploadOp = [[AFHTTPRequestOperation alloc]initWithRequest:fileUpRequest];
    //
    //        [_fileUploadOp setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    //                 startUp.enabled = NO;
    //                 [startUp setTitle:@"正在上传" forState:UIControlStateNormal];
    //                 CGFloat progress = ((float)totalBytesWritten) / totalBytesExpectedToWrite;
    //                 [uploadFileProgressView setProgress:progress animated:YES];
    //
    //            }];
    //
    //         [_fileUploadOp setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    //                startUp.enabled = NO;
    //                 [startUp setTitle:@"完成" forState:UIControlStateNormal];
    //                NSLog(@"upload finish ---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    //
    //             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //                     NSLog(@"error %@",error);
    //                 }];
    //
    //     }
}


@end
